﻿using DongFangGuoKai.WMS.NodeBussiness;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet;
using DongFangGuoKai.WMSPlatform.Service.InstructApp;
using DongFangGuoKai.WMSPlatform.Service.LogApp;
using DongFangGuoKai.WMSPlatform.Service.OutboundOrderDetail;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers
{
    /// <summary>
    /// AGV通知回调接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RCSNotifyController : ApiBaseController
    {
        private readonly IPalletService pallet;


        public ITReceivingOrderDetailService ReceivingOrderService { get; }
        public ITOutboundOrderDetailService OutboundOrderService { get; }
        public IConfiguration Configuration { get; }

        public IEnumerable<NodeBaseBusiness> NodeBase { get; }
        //指令
        public IInstructService InstructService { get; }

        public RCSNotifyController
            (

            ITReceivingOrderDetailService receivingOrderService,
            ITOutboundOrderDetailService outboundOrderService,
            IPalletService pallet, ILogService logService,
            IConfiguration configuration
, IEnumerable<NodeBaseBusiness> nodeBase, IInstructService instructService) : base(logService)
        {

            ReceivingOrderService = receivingOrderService;
            OutboundOrderService = outboundOrderService;
            this.pallet = pallet;
            Configuration = configuration;
            NodeBase = nodeBase;
            InstructService = instructService;
        }




        /// <summary>
        /// Agv回调通知
        /// </summary>
        /// <param name="callbackModel">回调消息体</param>
        /// <returns></returns>   
        [HttpPost]
        [Route("AgvCallback")]
        public async Task<IActionResult> AgvCallback(AgvCallbacNotifyModel callbackModel)
        {
            ResultRespone resultRespone = new ResultRespone();
            t_InterfaceLog log = null;
            try
            {

                string msg = string.Empty;
                bool result = true;
                CreateInterfaceLog("AGV回调通知", "", 2, callbackModel.ToJson(), out log);
                var instruct = await InstructService.GetInstructByBussinessGroupId(new Guid(callbackModel.taskCode));
                if (instruct != null)
                {
                    #region 通用处理逻辑
                    //var nodeBase = NodeBase.Where(t => t.InstructType == instruct.InstructType && t.WorkDeviceType == instruct.WorkDeviceType && t.DeviceAction == instruct.Action).FirstOrDefault();
                    //if (nodeBase == null)
                    //{
                    //    InterfaceCallFinished(log, false, "业务节点加载失败，请检查是否注入！！");
                    //}
                    //else
                    //{
                    //    switch (callbackModel.method)
                    //    {
                    //        //输送线空箱补货架
                    //        case "conveyorlineend":

                    //            result = nodeBase.CmdFinished(log, instruct, out msg);
                    //            break;

                    //        default:
                    //            break;
                    //    }


                    //}
                    #endregion

                    //AGV任务完成成功
                    if (callbackModel.method == "conveyorlineend")  //输送线结束
                    {
                        

                        var nodeBase = NodeBase.Where(t => t.InstructType == instruct.InstructType && t.WorkDeviceType == instruct.WorkDeviceType && t.DeviceAction == instruct.Action).FirstOrDefault();
                        if (nodeBase == null)
                        {
                            msg = "业务节点加载失败，请检查是否注入！！";
                            result = false;

                        }
                        else
                        {
                            result = nodeBase.CmdFinished(log, instruct, out msg);
                        }
                    }
                    if (callbackModel.method == "outbin")
                    {
                        if (instruct.InstructType == EmInstructType.In && instruct.WorkDeviceType == EmWorkDeviceType.AGV && instruct.Action == EmDeviceAction.Transport)
                        {
                            //入库完成
                            //var res = pallet.UpdPalletCellCode(instruct.PalletBarcode, instruct.ExpectedToLocation, out var errMsg);
                            var res = ReceivingOrderService.NewExecInstructFinishedMaterials(instruct, out string errorMsg);
                            if (res == false)
                            {
                                msg = errorMsg;
                                result = false;
                            }
                        }
                        else if (instruct.InstructType == EmInstructType.Out && instruct.WorkDeviceType == EmWorkDeviceType.AGV && instruct.Action == EmDeviceAction.Transport)
                        {
                            //样品箱号到输送线上
                            var res = OutboundOrderService.SampleToConveyor(instruct, out string errorMsg);
                            //样品箱号到出库位置
                            //var res = OutboundOrderService.CompleteOutBound(instruct, out string errorMsg);
                            if (res == false)
                            {
                                msg = errorMsg;
                                result = false;
                            }
                        }
                        else
                        {
                            msg = "未查询到指令！";
                            result = false;
                        }
                    }
                    await InstructService.AddAgvInstructAsync(new t_AgvInstruct()
                    {
                        RequestId = instruct.Id.ToString(),
                        RequestUrl = "",
                        RequstBody = JsonConvert.SerializeObject(callbackModel),
                        RequstType = (int)AgvRequstType.Notify,
                        Respone = JsonConvert.SerializeObject(resultRespone),
                        Success = true,
                        CreateDate = DateTime.Now,
                        CreateUserId = 0,
                        CreateUserName = "AGV"
                    });
                    InterfaceCallFinished(log, result, msg);



                }

                resultRespone.code = result ? "0" : "1";
                resultRespone.message = msg;
                resultRespone.reqCode = callbackModel.reqCode;

            }
            catch (Exception ex)
            {

                resultRespone.code = "1";
                resultRespone.message = ex.Message;
                resultRespone.reqCode = callbackModel.reqCode;
            }

            return Ok(resultRespone);
        }



    }
}
